#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
挂机系统问题修复脚本
用于修复测试中发现的问题
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from datetime import datetime, timedelta
from database.models import Character, CharacterClass, CharacterStatus
from database import db_manager
from src.idle.mysql_idle_manager import MySQLIdleManager

def fix_character_status_inconsistency():
    """
    修复角色状态与挂机记录不一致的问题
    """
    print("\n=== 修复角色状态不一致问题 ===")
    
    try:
        # 查找状态不一致的角色（使用is_idle字段）
        query = """
            SELECT c.id, c.name, c.is_idle, 
                   COUNT(ir.id) as active_records
            FROM characters c
            LEFT JOIN idle_records ir ON c.id = ir.character_id AND ir.status = 'active'
            GROUP BY c.id, c.name, c.is_idle
            HAVING (c.is_idle = 1 AND active_records = 0) 
                OR (c.is_idle = 0 AND active_records > 0)
        """
        
        inconsistent_records = db_manager.execute_query(query)
        
        if not inconsistent_records:
            print("✅ 没有发现状态不一致的角色")
            return
        
        print(f"发现 {len(inconsistent_records)} 个状态不一致的角色，开始修复...")
        
        for record in inconsistent_records:
            char_id = record['id']
            char_name = record['name']
            current_is_idle = record['is_idle']
            active_records = record['active_records']
            
            print(f"\n处理角色: {char_name} (ID: {char_id})")
            print(f"  当前is_idle状态: {current_is_idle}")
            print(f"  活跃挂机记录数: {active_records}")
            
            if current_is_idle == 1 and active_records == 0:
                # 角色is_idle为true但没有活跃挂机记录，应该改为false
                update_query = "UPDATE characters SET is_idle = 0 WHERE id = %s"
                db_manager.execute_update(update_query, (char_id,))
                print(f"  ✅ 已将is_idle从 true 修改为 false")
                
            elif current_is_idle == 0 and active_records > 0:
                # 角色is_idle为false但有活跃挂机记录，应该改为true
                update_query = "UPDATE characters SET is_idle = 1 WHERE id = %s"
                db_manager.execute_update(update_query, (char_id,))
                print(f"  ✅ 已将is_idle从 false 修改为 true")
        
        print("\n✅ 角色状态不一致问题修复完成")
        
    except Exception as e:
        print(f"❌ 修复角色状态不一致问题失败: {e}")

def fix_expired_idle_records():
    """
    修复超时的挂机记录
    """
    print("\n=== 修复超时挂机记录问题 ===")
    
    try:
        # 获取最大挂机时长配置
        config_query = "SELECT config_value FROM system_config WHERE config_key = 'max_idle_hours'"
        config_result = db_manager.execute_query(config_query)
        max_hours = int(config_result[0]['config_value']) if config_result else 4
        
        print(f"最大挂机时长: {max_hours} 小时")
        
        cutoff_time = datetime.now() - timedelta(hours=max_hours)
        
        # 查找超时的活跃挂机记录
        query = """
            SELECT ir.id, ir.character_id, ir.location_id, ir.start_time, 
                   TIMESTAMPDIFF(HOUR, ir.start_time, NOW()) as hours_elapsed,
                   c.name as character_name
            FROM idle_records ir
            JOIN characters c ON ir.character_id = c.id
            WHERE ir.status = 'active' AND ir.start_time <= %s
        """
        
        expired_records = db_manager.execute_query(query, (cutoff_time,))
        
        if not expired_records:
            print("✅ 没有发现超时的挂机记录")
            return
        
        print(f"发现 {len(expired_records)} 个超时的挂机记录，开始修复...")
        
        # 使用挂机管理器来处理超时记录
        idle_manager = MySQLIdleManager()
        
        for record in expired_records:
            char_id = record['character_id']
            char_name = record['character_name']
            hours_elapsed = record['hours_elapsed']
            
            print(f"\n处理角色: {char_name} (ID: {char_id})")
            print(f"  已挂机: {hours_elapsed} 小时")
            
            try:
                # 使用自动结算功能处理超时记录
                result = idle_manager.auto_settle_expired_idle()
                
                if result['success']:
                    print(f"  ✅ 自动结算成功")
                    if 'exp_gained' in result:
                        print(f"     获得经验: {result['exp_gained']}")
                    if 'gold_gained' in result:
                        print(f"     获得金币: {result['gold_gained']}")
                    if result.get('restarted', False):
                        print(f"     已重新开始挂机")
                else:
                    print(f"  ❌ 自动结算失败: {result.get('message', '未知错误')}")
                    
            except Exception as e:
                print(f"  ❌ 处理失败: {e}")
                
                # 如果自动结算失败，手动结束挂机记录
                try:
                    end_time = datetime.now()
                    
                    # 计算收益（简化版本）
                    duration_hours = (end_time - record['start_time']).total_seconds() / 3600
                    # 限制最大收益时长
                    effective_hours = min(duration_hours, max_hours)
                    
                    # 获取地点信息
                    location_query = "SELECT base_exp_rate FROM idle_locations WHERE id = %s"
                    location_result = db_manager.execute_query(location_query, (record['location_id'],))
                    base_exp_rate = location_result[0]['base_exp_rate'] if location_result else 10
                    
                    # 简单计算经验收益
                    exp_gained = int(base_exp_rate * effective_hours * 100)  # 基础每小时100经验
                    
                    # 先查找对应的挂机记录ID
                    record_query = """
                        SELECT id FROM idle_records 
                        WHERE character_id = %s AND status = 'active'
                        ORDER BY start_time DESC LIMIT 1
                    """
                    record_result = db_manager.execute_query(record_query, (char_id,))
                    
                    if record_result:
                        record_id = record_result[0]['id']
                        
                        # 结束挂机记录
                        update_query = """
                            UPDATE idle_records 
                            SET status = 'completed', end_time = %s, exp_gained = %s, duration_seconds = %s
                            WHERE id = %s
                        """
                        duration_seconds = int(effective_hours * 3600)
                        db_manager.execute_update(update_query, (end_time, exp_gained, duration_seconds, record_id))
                        
                        # 更新角色状态
                        char_update_query = "UPDATE characters SET is_idle = 0 WHERE id = %s"
                        db_manager.execute_update(char_update_query, (char_id,))
                        
                        print(f"  ✅ 手动结算完成，获得经验: {exp_gained}")
                    else:
                        print(f"  ❌ 未找到对应的挂机记录")
                    
                except Exception as manual_error:
                    print(f"  ❌ 手动结算也失败: {manual_error}")
        
        print("\n✅ 超时挂机记录修复完成")
        
    except Exception as e:
        print(f"❌ 修复超时挂机记录失败: {e}")

def validate_fixes():
    """
    验证修复结果
    """
    print("\n=== 验证修复结果 ===")
    
    try:
        # 1. 重新检查角色状态一致性
        print("\n1. 检查角色状态一致性...")
        
        query = """
            SELECT c.id, c.name, c.is_idle, 
                   COUNT(ir.id) as active_records
            FROM characters c
            LEFT JOIN idle_records ir ON c.id = ir.character_id AND ir.status = 'active'
            GROUP BY c.id, c.name, c.is_idle
            HAVING (c.is_idle = 1 AND active_records = 0) 
                OR (c.is_idle = 0 AND active_records > 0)
        """
        
        inconsistent_records = db_manager.execute_query(query)
        
        if inconsistent_records:
            print(f"❌ 仍有 {len(inconsistent_records)} 个状态不一致的角色")
            for record in inconsistent_records:
                print(f"   角色: {record['name']}, is_idle: {record['is_idle']}, 活跃记录: {record['active_records']}")
        else:
            print("✅ 角色状态一致性问题已解决")
        
        # 2. 重新检查超时记录
        print("\n2. 检查超时挂机记录...")
        
        config_query = "SELECT config_value FROM system_config WHERE config_key = 'max_idle_hours'"
        config_result = db_manager.execute_query(config_query)
        max_hours = int(config_result[0]['config_value']) if config_result else 4
        
        cutoff_time = datetime.now() - timedelta(hours=max_hours)
        
        query = """
            SELECT COUNT(*) as count
            FROM idle_records ir
            WHERE ir.status = 'active' AND ir.start_time <= %s
        """
        
        expired_count = db_manager.execute_query(query, (cutoff_time,))
        count = expired_count[0]['count'] if expired_count else 0
        
        if count > 0:
            print(f"❌ 仍有 {count} 个超时的挂机记录")
        else:
            print("✅ 超时挂机记录问题已解决")
        
        # 3. 显示当前系统状态
        print("\n3. 当前系统状态概览...")
        
        status_query = """
            SELECT 
                CASE WHEN c.is_idle = 1 THEN 'idle' ELSE 'normal' END as status,
                COUNT(*) as count
            FROM characters c
            GROUP BY c.is_idle
        """
        
        status_counts = db_manager.execute_query(status_query)
        
        print("   角色状态分布:")
        for status in status_counts:
            print(f"     {status['status']}: {status['count']} 个角色")
        
        active_idle_query = """
            SELECT COUNT(*) as count
            FROM idle_records
            WHERE status = 'active'
        """
        
        active_idle_count = db_manager.execute_query(active_idle_query)
        count = active_idle_count[0]['count'] if active_idle_count else 0
        print(f"   活跃挂机记录: {count} 个")
        
    except Exception as e:
        print(f"❌ 验证修复结果失败: {e}")

def main():
    """
    主修复函数
    """
    print("挂机系统问题修复脚本")
    print("=" * 50)
    
    # 测试数据库连接
    if not db_manager.test_connection():
        print("❌ 数据库连接失败，无法进行修复")
        return
    
    print("✅ 数据库连接成功")
    
    # 执行修复
    fix_character_status_inconsistency()
    fix_expired_idle_records()
    
    # 验证修复结果
    validate_fixes()
    
    print("\n" + "=" * 50)
    print("修复完成！")
    print("\n建议:")
    print("1. 定期运行 test_idle_system_issues.py 检查系统状态")
    print("2. 考虑添加定时任务自动处理超时挂机记录")
    print("3. 在挂机开始/结束时增加更严格的状态验证")
    print("4. 添加系统监控和告警机制")

if __name__ == "__main__":
    main()